import React, { Component } from 'react';
import moment from 'moment'
import { connect } from 'react-redux'  
import { Modal, Form, Input, Select, DatePicker,message,Tree,TreeSelect, Row, Col,TimePicker, Radio, Button} from 'antd';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option =Select.Option;
const TreeNode = Tree.TreeNode;
var dayList = ['1', '2','3', '4','5', '6','7', '8','9', '10','11', '12','13', '14','15', '16','17', '18','19', '20','21', '22','23', '24','25', '26','27', '28','29', '30','31'];

class AddPlanModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,   
    };
  }

  okHandler = () => {
     const { onOk, cycletime } = this.props;
     this.props.form.validateFields((err, values) => {
      if (!err) {        
        var list = [];
        cycletime.patrolPlanTimes.map(d=>{
          var dr = {
            ...d,
          };
         if(dr.startTime&&dr.endTime){
           dr.startTime = new moment(dr.startTime).format("HH:mm");
           dr.endTime = new moment(dr.endTime).format("HH:mm");
           list.push(dr);
         }        
          
        })
        if(list!=null&&list.length>0){
           values = {
            ...values,
            cycleType:cycletime.cycleType,
            patrolPlanTimes: list,
           }
        
         onOk(values);
        }else{
            message.error('请选择巡检时间');
        }
      
      }
     });
  };
 
  onRadioChange = (e) => {
    const { onRadioChange } = this.props;
    onRadioChange(e.target.value);
  }; 
  handleRoomChange = (value) => {
    const { handleRoomChange } = this.props;
    handleRoomChange(value);
  }; 
  
  render() {
    const { children, dispatch,item,roomList,userList,isShowUser,rackList,editDetailHandler,addDetailHandler,cycletime } = this.props;    
    const { getFieldDecorator } = this.props.form;   
    
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }; 
    const formItemLayout4 = {
      labelCol: { span: 7 },
      wrapperCol: { span: 15 },
    }; 
    const formItemLayout1 = {
      labelCol: { span: 12 },
      wrapperCol: { span: 12 },
    };
    const formItemLayout3 = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 10 },
      wrapperCol: { span: 11 },
    };
    const getDay = data => data.map((item) => {
     return <Option key={item+''}>{item}日</Option>
    })
    const cycletimeChange = function(e){
      dispatch({
        type: "patrolPlan/upState",
        payload: {
          cycletime: {
            patrolPlanTimes: [],
            cycleType: e.target.value,
          }
        }
      })
    }
    const addIns = () => {
      cycletime.patrolPlanTimes.push({})
      dispatch({
        type: "patrolPlan/upState",
        payload: {
          cycletime: cycletime,
        }
      })
    }
    const delIns = (ind) => {
      cycletime.patrolPlanTimes.splice(ind,1);
      dispatch({
        type: "patrolPlan/upState",
        payload: {
          cycletime: cycletime,
        }
      })
    }
    const changeIns = (value,ind,name) => {
      //console.log(value)
      // console.log(name)
      cycletime.patrolPlanTimes[ind][name] = value;
      dispatch({
        type: "patrolPlan/upState",
        payload: {
          cycletime: cycletime,
        }
      })
    }
    const showIns = data => {
      switch(data.cycleType){
        case 1:
         return data.patrolPlanTimes.map((item,index) => (
          <div key={index}>
            <div style={{float:"left",marginRight:10}}>
              开始时间:  <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left",marginRight:10}}>
              结束时间:  <TimePicker format="HH:mm" value={item.endTime} onChange={(e)=>changeIns(e,index,"endTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left"}}><Button type="danger" onClick={()=>delIns(index)}>删除</Button></div>
            <div style={{display:"block",height:0,clear:"both"}}></div>
          </div>
         ));
        case 2:
         return data.patrolPlanTimes.map((item,index) => (
          <div key={index}>
            <div style={{float:"left",marginRight:10}}>
              <Select value={item.day!=null?item.day+"":undefined} placeholder="选择时间" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 60 }} >
                <Option value="1">周一</Option>
                <Option value="2">周二</Option>
                <Option value="3">周三</Option>
                <Option value="4">周四</Option>
                <Option value="5">周五</Option>
                <Option value="6">周六</Option>
                <Option value="7">周日</Option>
              </Select> 
            </div>
            <div style={{float:"left",marginRight:10}}>
                开始时间:  <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left",marginRight:10}}>
                结束时间:  <TimePicker format="HH:mm" value={item.endTime} onChange={(e)=>changeIns(e,index,"endTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
            <div style={{display:"block",height:0,clear:"both"}}></div>
          </div>
         ));
        case 3:
         return data.patrolPlanTimes.map((item,index) => (
          <div key={index}>
            <div style={{float:"left",marginRight:10}}>
              <Select value={item.day!=null?item.day+"":undefined} placeholder="选择日期" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 60 }} >        
                 {getDay(dayList)}                       
              </Select>
            </div>
            <div style={{float:"left",marginRight:10}}>
              开始时间:  <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left",marginRight:10}}>
              结束时间:  <TimePicker format="HH:mm" value={item.endTime} onChange={(e)=>changeIns(e,index,"endTime")} style={{width:'90px'}}/></div>
            <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
            <div style={{display:"block",height:0,clear:"both"}}></div>
          </div>
         ));
      }
    }
  
    const getUser = data => data.map((item) => {
     return <Option key={item.id_+''}>{item.name}</Option>
    })

    const getRoom = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })

    return (
      <span>
              <Modal
                    maskClosable= {this.props.maskClosable}
                    confirmLoading= {this.props.confirmLoading}
                    title={this.props.title}
                    visible={this.props.visible}
                    onOk={this.okHandler}
                    width={600}
                    onCancel={this.props.onCancel}
                    key={this.props.newKey}
              >
         
                <Form layout='horizontal' onSubmit={this.okHandler}>
                      <FormItem style={{marginBottom:'0px'}}>
                        {getFieldDecorator('id',{initialValue:item.id_})(
                          <Input type="hidden"/>
                        )}
                      </FormItem> 
                      <FormItem
                          {...formItemLayout}
                            label="巡检计划名称"
                            hasFeedback
                          >
                          {
                            getFieldDecorator('name', {
                              initialValue: item.name,
                              rules: [{
                                required: true, whitespace: true, message: '请输入巡检计划名称',
                              },{
                                max:20,message: '巡检计划名称不能超过20个字',
                              }]
                            })(<Input placeholder="请输入巡检计划名称"/>)
                          }
                      </FormItem>  
                      <Row>
                      <Col span={12}>
                        <FormItem
                          {...formItemLayout1}
                          label="开始日期"
                          hasFeedback
                        >
                          {getFieldDecorator('startDate', {
                                initialValue: item.startDate?moment(item.startDate):null,   
                                rules: [{
                                    required: true, type: 'object',whitespace: true, message: '请选择开始时间',
                                  }]
                            })(
                                <DatePicker format="YYYY-MM-DD" style={{width:'130px'}}/>
                            )}
                        </FormItem> 
                        </Col>
                        <Col span={12}>
                           <FormItem
                              {...formItemLayout2}
                              label="结束日期"
                              hasFeedback
                          >
                             {getFieldDecorator('endDate', {
                                initialValue: item.endDate!=null?moment(item.endDate):null,   
                                rules: [{
                                  required: true, type: 'object',whitespace: true, message: '请选择开始时间',
                                 }]
                               })(
                                <DatePicker format="YYYY-MM-DD" style={{width:'130px'}}/>
                              )}
                         </FormItem> 
                        </Col>
                     </Row> 
                     <Row>
                      <Col span={14}>  
                          <FormItem
                            {...formItemLayout3}
                            label="重复周期"
                          >
                                <RadioGroup value={cycletime.cycleType} onChange={cycletimeChange}>
                                  <Radio value={1}>每天</Radio>
                                  <Radio value={2}>每周</Radio>
                                  <Radio value={3}>每月</Radio>
                                </RadioGroup>
                          </FormItem>    
                       </Col>
                       <Col span={10}>  
                             <FormItem
                                {...formItemLayout4}
                                label="负责人"
                                hasFeedback
                              >
                              {getFieldDecorator('operatorBy', {
                                  initialValue:  item.operatorBy_ == undefined? undefined : item.operatorBy_+"",   
                                  rules: [{
                                    required: true, whitespace: true, message: '请选择巡检负责人',
                                  }]
                              })(
                                <Select
                                    style={{width:'130px'}}
                                    placeholder="选择巡检负责人"
                                    optionFilterProp="children"  
                                >
                                    {getUser(userList)}
                                </Select>   
                              )}
                          </FormItem>    
                         </Col>
                      </Row>                  
                          <FormItem
                            {...formItemLayout}
                            required
                            label="巡检时间"
                          >                          
                            {showIns(cycletime)}
                            <div>
                              <Button type="primary" size="large" onClick={addIns}>添加时间</Button>
                            </div>
                         </FormItem>
                      
                         <FormItem
                            {...formItemLayout}
                              label="巡检机房"
                              hasFeedback
                            >
                            {getFieldDecorator('roomId', {
                              initialValue:  item.roomId_ == undefined? undefined : item.roomId_+"",   
                              rules: [{
                                required: true, whitespace: true, message: '请选择巡检机房',
                              }]
                            })(
                              <Select
                                showSearch
                                placeholder="请选择巡检机房"
                                optionFilterProp="children"
                              >
                                {getRoom(roomList)}
                              </Select>
                            )}  
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="备注"
                            hasFeedback
                        >
                        {
                          getFieldDecorator('desc', {
                              initialValue:  item.desc,  
                              rules: [{ max: 200, message: '备注信息 200 字符以内' },]
                          })(<Input type="textarea" autosize={{ minRows: 3, maxRows: 6 }}/>)
                        }
                        </FormItem>     
                   
                </Form>              
        </Modal>        
      </span>
    );
  }
    
}

export default Form.create()(AddPlanModal)